#!/usr/bin/python3
# coding: utf-8
from flask import render_template, url_for, session, redirect, request, flash, abort
from werkzeug.security import check_password_hash
from app import app
import functools
import hashlib
import os
from flask_admin.contrib.sqla import ModelView 
from flask_wtf import FlaskForm


@app.before_request
def csrf_protect():
	if request.method == "POST" and '/admin' not in request.path:
		token = session.pop('_csrf_token', None)
		if not token or token != request.form.get('_csrf_token'):
			abort(404)
			
def generate_csrf_token():
	if '_csrf_token' not in session:
		session['_csrf_token'] = hashlib.sha1(os.urandom(24)).hexdigest()
	return session['_csrf_token']

app.jinja_env.globals['csrf_token'] = generate_csrf_token    

def login_required(fn):
	@functools.wraps(fn)
	def inner(*args,**kwargs):
		if session.get('logged_in'):
			return fn(*args,**kwargs)
		return redirect(url_for('login',next=request.path))
	return inner

@app.errorhandler(404)
def page_not_found(e):
	text = '404'
	return render_template('404.html', text=text), 404

@app.route('/')
@app.route('/index')
def index():
	posts = {}
	pagination = {}
	return render_template("index.html", posts=posts, pagination=pagination, is_draft=False)

@app.route('/draft')
def draft():
	posts = {}
	pagination = {}
	return render_template("index.html", posts=posts, pagination=pagination, is_draft=False)

@app.route('/create')
def create():
	posts = {}
	pagination = {}
	return render_template("index.html", posts=posts, pagination=pagination, is_draft=False)

@app.route('/login', methods=['POST','GET'])
def login():
	next_url=request.args.get('next') or request.form.get('next')
	if request.method == 'POST' and request.form.get('password'):
		if not check_password_hash(app.config['PASSWORD_HASH'],request.form.get('password')):
			session['logged_in']=True
			session.permanent = True  # Use cookie to store session.
			flash('你已经成功登陆.','success')
			print(request.path)
			return redirect(next_url or url_for('index'))
		flash('密码错误，请重新输入.','danger')
	return render_template('login.html',next=next_url)

@app.route('/logout', methods=['GET','POST'])
@login_required
def logout():
	if request.method == 'POST':
		session.clear()
		flash('你已经成功登出本站.','success')
		print(request.path)
		return redirect(url_for('index'))
	return render_template('logout.html')


class PostAdminView(ModelView):
	form_base_class = FlaskForm
	column_display_pk = True
	can_create = False
	column_list = ('id','title','category','published')

class CategoryAdminView(ModelView):
	form_base_class = FlaskForm
	column_display_pk = True
	can_create = True
	#Category模型中不能定义__init__方法，否则无法在admin创建category对象

